<?php
require_once "Zen/View/Helper/Image/lib/WideImage.php";
class Zen_View_Helper_Image_Multi1 extends Zend_View_Helper_Abstract {

	private $actions = array ();
	private $images = null;
	private $_data = null;
	
	private $_options = array(
        'module'             		=> '',
        'cache_dir'                 => '',
		'cache'						=> null,
		'actions'					=> array(),
    );
    
    private $_option = null;
	
	private function _init() {
		try {
			$module = Zend_Controller_Front::getInstance()->getRequest()->getModuleName();
		} catch(Exception $e) {
			$module = $this->_option->getOption('module');
		}
		$cache = Zen_Cache_Factory::get("images_$module");
		$cache_dir = Zend_Registry::get ( 'cnf' )->cache_dir . "images_$module/";
		$this->_option->setOption('cache', $cache)
					  ->setOption('cache_dir', $cache_dir);
		return $this;
	}
	
	private function _prepareImages() {
		$data = $this->_data;
		$ids = explode ( ',', $data ); 
		if (! count($ids) ) 
			return $this;
				
		$images = array();
		$actions = $this->actions;
		$this->_option->setOption('actions', $actions);
		foreach ( $ids as $id ) {
			$images[] = new Image_Item($id, $this->_option->getOptions());
		}
		return $images;
	}
	
	public function image_Multi1($field, $options = array() ) {
		$this->_option = new Zen_Option($this->_options, $options);
        $this->_init();
        $this->_data = $field;
        $this->actions = null;
        return $this;
	}
	
	public function __call($method, $args) {
		$this->actions [] = array ('method' => $method, 'args' => $args );
		return $this;
	}
	
	public function getOne() {
		$images = $this->_prepareImages();
		$image = array_shift($images) ;
		$image = $image->execute();
		return $image;
	}
	
	public function getMany() {
		$images = $this->_prepareImages();
		foreach ($images as $key=>$image) {
			$images[$key] = $image->execute();
		}
		return $images;
	}
	
}
	

class Image_Item {
	
	private $_options = array(
        'id'             		=> null,
        'cache_dir'             => '',
		'cache'					=> null,
		'quality'				=> 100,
		'show_dimensions'		=> false,
		'class'					=> null,
		'actions'				=> array(),
    );
    
    private $_infos = array (
    	'id'		=> null,
    	'img_url'	=> null,
    	'url'		=> null,
    	'img_tag'	=> null,
    	'height'	=> null,
    	'width'		=> null,
    	'alt'		=> null,
    	'hash_name'	=> null,
    	'name'		=> null,
    	'type'		=> null,
    	'crop'		=> null,
    	'style'		=> null,
    );
    
    private $_option = null;
    private $_info = null;
    
	private $_id = null;
	
	public function __construct($id, $options = array()) {
		$id = trim ( preg_replace ( '/\D/', '', $id ) );
		if (! $id) 
			throw new Zend_Exception();
		$this->_option = new Zen_Option($this->_options, $options);
		$this->_info = new Zen_Option($this->_infos);
		$this->_info->setOption('id',$id);

		$hash_name = $this->_getHashName();
		$this->_info->setOption('hash_name',$hash_name);
		$cache = $this->_option->getOption('cache');
		
		$image = $cache->load($hash_name);
		if (! $image) {
			$image = $this->_getImageRow();
			foreach (array('alt','crop','img_url','width','height','type') as $attr) {
				$this->_info->setOption($attr,$image[$attr]);
			}
		}
		$cache_dir = $this->_option->getOption('cache_dir');
		$image_name = $cache_dir . $hash_name . '.' . $image['type'];
		$this->_info->setOption('name',$image_name);
		$this->_info->setOption('url',str_replace ( ROOT_PATH, '', $image_name ));
		
		return $this;
	}
	
	public function execute() {
		$cache_file_path = $this->_info->getOption('name');
		$native_file_path = ROOT_PATH . $this->_info->getOption('img_url');
		$actions = $actions = $this->_option->getOption('actions');
		if (! file_exists ( $native_file_path)) 
			return;
		$cache = $this->_option->getOption('cache');
		$hash_name = $this->_info->getOption('hash_name');
		if (! file_exists ( $cache_file_path )) {
			if (count ( $actions ) > 0) {
				$Wimage = WideImage::load ( $native_file_path );
				foreach ( $actions as $action ) {
					$make=true;
					if(($action ['method']=='crop')&&(sizeof($action ['args'])==0)){
						$crop = $this->_info->getOption('crop');
						if( $crop != "" ){
							$cropParams=Zend_Json_Decoder::decode( $crop );
							$params=array(
								$cropParams['perc_x']."%",
								$cropParams['perc_y']."%",
								$cropParams['perc_width']."%",
								$cropParams['perc_height']."%",
							);
							$action ['args']=$params;
						}else{
							$make=false;
						}
					}
					if(($action ['method']=='merge')){
						$action ['args'][0]=WideImage::load($action ['args'][0]);
					}
					if ( $Wimage&&($make==true) ) {
						if ( method_exists ( $Wimage, $action ['method'] )) {
							$Wimage = call_user_func_array ( array ($Wimage, $action ['method'] ), $action ['args'] );
						}
					}
				}
				$this->_info->setOption('width',$Wimage->getWidth () );
				$this->_info->setOption('height',$Wimage->getHeight () );
				
				$type = $this->_info->getOption('type');
				if ($type == "png") {
					$Wimage->saveToFile ( $cache_file_path );
				}
				if ($type == "jpg") {
					$Wimage->saveToFile ( $cache_file_path, $this->_option->getOption('quality') );
				}
				if ($type == "gif") {
					$Wimage->saveToFile ( $cache_file_path );
				}
			}else{
				copy( $native_file_path,  $cache_file_path);
			}
			$this->_info->setOption('img_tag', $this->_getImgTag() );
			$this->_info->setOption('style', $this->_getStyle() );
			$cache->save($this->_info->getOptions(),$hash_name);
			chmod($cache_file_path, 0777);
		}
		return $cache->load($hash_name);
	}
	
	private function _getImgTag() {
		$alt = 'alt="' . $this->_info->getOption('alt') . '"';
		$dimensions = '';
		if ($this->_option->getOption('show_dimensions')) {
			$dimensions .= 'width="' . $this->_info->getOption('width') . '"';
			$dimensions .= 'height="' . $this->_info->getOption('height') . '"';
		}
		$class = '';
		if ($this->_option->getOption('class')) {
			$class .= 'class="' . $this->_info->getOption('class') . '"';
		} 
		$img_tag = '<img ' . 
					$class . ' '. 
					$alt . ' ' . 
					$dimensions . ' ' .  
					'src="' . $this->_info->getOption('url') . '"  />';
		$img_tag = preg_replace ( '/\040+/', ' ', $img_tag);
		return $img_tag;
	}
	
	private function _getStyle() {
		$url = $this->_info->getOption('url');
		$style = "background-image:url($url);";
		return $style;
	}

	private function _getHashName() {
		$id = $this->_info->getOption('id');
		$actions = $this->_option->getOption('actions');
		$quality = $this->_option->getOption('quality'); 
		return $id . '_' . md5 (serialize ( $actions ) . $quality . $id);
	}
	
	private function _getImageRow() {
		$id = $this->_info->getOption('id');
		$imageModel = new Images_Model_Imageslist();
		$image = $imageModel->getTable()->find($id)->current ();
		$image = $image->toArray();
		if (! $image) {
			throw new Zend_Exception();
		}
		return $image;
	}
	
	
}